package week13;

import java.util.ArrayList;
import java.util.Random;

public class RedEnvelope {
    public class RandomRedEnvelopes {
        public void main(String[] args) {
            ArrayList<Integer> result = new ArrayList<>();
            int total = 100;

            Random random = new Random();

            for (int i = 0; i < 5; i++) {
                int randomValue;
                if (i == 0) {
                    // 第一次随机取值范围，确保后面还有足够空间产生不同值
                    randomValue = random.nextInt(total - 4) + 1;
                } else if (i == 4) {
                    // 最后一次直接用剩余值
                    randomValue = total - sumList(result);
                } else {
                    // 中间几次根据已生成的值动态确定取值范围
                    int minValue = 1;
                    int maxValue = total - sumList(result) - (4 - i);
                    randomValue = random.nextInt(maxValue - minValue + 1) + minValue;
                }

                result.add(randomValue);
                total -= randomValue;
            }

            System.out.println("生成的5个随机值分别为：");
            for (int value : result) {
                System.out.print(value + " ");
            }
            System.out.println("\n它们的总和为：" + sumList(result));
        }

        public int sumList(ArrayList<Integer> list) {
            int sum = 0;
            for (int value : list) {
                sum += value;
            }
            return sum;
        }
    }

}
